const {contractModel} = require('../modules/contracts.js');
const {carModel}=require('../modules/car');
const {advertiseModel}=require('../modules/advertise.js');
const {houseModel}=require('../modules/house.js');
const { uploadFiles, moveFiles, deleteFiles } = require('../utils/handleFiles');
const path = require('path');

async function getContracts(req, res, next) {
    const data = req.query;
    const value = data.searchObj.value;
    const currentPage = data.currentPage;
    const pageSize = data.pageSize;
    const result= await contractModel.find({ $or: [{ leaseeContacts: { $regex: value, $options: '$i' } }, { numbers: { $regex: value, $options: '$i' } }, { contractNumber: { $regex: value, $options: '$i' } }] }).populate('carId').populate('advertiseId').populate('houseId').limit(Number(pageSize)).skip((Number(currentPage)-1)*Number(pageSize));
    const total=await contractModel.find({ $or: [{ leaseeContacts: { $regex: value, $options: '$i' } }, { numbers: { $regex: value, $options: '$i' } }, { contractNumber: { $regex: value, $options: '$i' } }] }).countDocuments();
    const pages=Math.ceil(total/pageSize);
    if(result.length>0){
        res.send({
            message:"获取客户数据成功",
            code:200,
            result,
            total,
            pages
        });
    }else{
        res.send({
            message:"获取客户数据失败",
            code:500
        });  
    }
}



async function addContracts(req, res, next) {
    const data=req.body;
    const result=await contractModel.create(data);
    if(result){
        res.send({
            message:"添加合同成功",
            code:200,
           data:result
        });
    }else{
        res.send({
            message:"添加合同失败",
            code:500
        });
    }

}



//删除租合同数据
async function delContractData (req, res, next) {
    const data=req.body;
    const obj=await contractModel.find(data);
    const result=await contractModel.deleteOne(data);
    if(result.deletedCount>0){
        if(obj[0]){
            switch(obj[0].contractName){
                case '车位租赁合同': 
                const id1=obj[0].carId;
               await carModel.deleteOne({_id:id1})
                break;
                case '广告位租赁合同': 
                const id2=obj[0].advertiseId; 
                await advertiseModel.deleteOne({_id:id2})
                break;
                case '房屋租赁合同': 
                const id3=obj[0].houseId; 
                await houseModel.deleteOne({_id:id3})
                break;
            }
        }
        res.send({
            message:"删除赁车位合同数据成功",
            code:200,
        });
    }else{
        res.send({
            message:"删除赁车位合同数据失败",
            code:500
        });  
    }

}



//通过ID获取合同数据
async function getcontractsById (req, res, next) {
    const _id=req.params;
    const result=await contractModel.find({_id}).populate('carId').populate('advertiseId').populate('houseId');
    let data=[];
    if(result.length>0){
        if(result[0]){
            switch(result[0].contractName){
                case '车位租赁合同': 
                const id1=result[0].carId;
                data=await carModel.find({_id:id1})
                break;
                case '广告位租赁合同': 
                const id2=result[0].advertiseId; 
                data=await advertiseModel.find({_id:id2})
                break;
                case '房屋租赁合同': 
                const id3=result[0].houseId; 
                data=await houseModel.find({_id:id3})
                break;
            }
        res.send({
            message:"获取合同数据成功",
            code:200,
            result:data[0]
        });
    }else{
        res.send({
            message:"获取同数据失败",
            code:500
        });  
    }
}



}








//修改广告位租赁合同
async function updateContracts(req, res, next){
    var data=req.body;
    const {_id,
        contractNumber,
        tenant,
        signingDate,
        representative,
        tenantContacts,
        contractType,
        term,
        off_hire,
        start_date,
        area,
        earnestMoney,
        agencyfee,
        isRentMoney,
        totalMoney,
        increase,
        earnestExplain,
        remark,
        contractName}=data;
    if (data.accessory) {
        // 获取路径中的图片名称
        const filename = path.basename(data.accessory);
        // 移动图片
        moveFiles({
            fromPath: './public/temp',
            toPath: './public/images',
            filename
        })
           // 删除临时文件夹
        deleteFiles('./public/temp');
        // 更改图片路径的数据
        data.accessory= 'http://localhost:3100/./images/' + filename;
    }
    
    const result=await contractModel.updateOne({_id},{
        contractNumber:data.contractNumber,//合同编号
        tenant:data.tenant, //租户  2
        signingDate:data.signingDate,//签订日期  2
        off_hire:data.off_hire,//停租日期   2
        start_date:data.start_date,//起租日期`  2
    });

    if(result.ok>0){
            const ctdata=await contractModel.find({_id}).populate('carId').populate('advertiseId').populate('houseId');
            switch(ctdata[0].contractName){
                case '车位租赁合同': 
                const id1=ctdata[0].carId;
                arrCt=await carModel.updateOne({_id:id1},{
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory:data.accessory,
                    contractName
                });
                break;
                case '广告位租赁合同': 
                const id2=ctdata[0].advertiseId; 
                data=await advertiseModel.updateOne({_id:id2}, {   contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory:data.accessory,
                    contractName});
                break;
                case '房屋租赁合同': 
                const id3=ctdata[0].houseId; 
                data=await houseModel.updateOne({_id:id3}, {
                    contractNumber,
                    tenant,
                    signingDate,
                    representative,
                    tenantContacts,
                    contractType,
                    term,
                    off_hire,
                    start_date,
                    area,
                    earnestMoney,
                    agencyfee,
                    isRentMoney,
                    totalMoney,
                    increase,
                    earnestExplain,
                    remark,
                    accessory:data.accessory,
                    contractName
                });
                break;
            }
            res.send({
                message:"更新合同成功",
                code:200
            });

        }
    else{
        res.send({
            message:"更新合同失败",
            code:500
        });
    }
}






function loadImg(req, res, next) {
    // 图片上传
    const uploadImages = uploadFiles({
        // 图片上传成功后的存储路径
        path: './public/temp',
        // key: 'file',
        size: 1000000
    });
    uploadImages(req, res, (error) => {
        if(error) {
            console.log('图片上传失败', error);
        } else {
            console.log('图片上传成功');
            // 输出上传成功后的图片信息
            res.send({
                message: '图片上传成功',
                code: 200,
                data: './temp/' + req.files[0].filename
            })
        }
    });
}






module.exports = { getContracts ,addContracts,delContractData,getcontractsById,loadImg,updateContracts}